module SideffectHelper
  def normalize_hash_value(h)
    sum = 0
    h.each_value do |value|
      sum += value
    end
    res = {}
    h.each do |key, value|
      res["#{key.to_s} (#{value})"] = (100.0 * value.to_f / sum.to_f).to_i
    end
    res
  end
  
  def filter_sql(options = {})
    options[:ratings_table_name] ||= 'r'
    sex_filter = case options[:sex]
                 when 'F'
                   "#{options[:ratings_table_name]}.sex = 'F'"
                 when 'M'
                   "#{options[:ratings_table_name]}.sex = 'M'"
                 when 'U'
                   "(#{options[:ratings_table_name]}.sex <> 'M' AND #{options[:ratings_table_name]}.sex <> 'F')"
                 else
                   '1'
                 end
    age_filter = case options[:age]
                 when '18'
                   "#{options[:ratings_table_name]}.age <= 18"
                 when '45'
                   "#{options[:ratings_table_name]}.age > 18 AND #{options[:ratings_table_name]}.age <= 45"
                 when '60'
                   "#{options[:ratings_table_name]}.age > 45 AND #{options[:ratings_table_name]}.age <= 60"
                 when 'inf'
                   "#{options[:ratings_table_name]}.age > 60"
                 when 'U'
                   "#{options[:ratings_table_name]}.age IS NULL"
                 else
                   '1'
                 end
    time_taken_filter = case options[:time_taken] 
                        when 'week'
                          "#{options[:ratings_table_name]}.days_taken <= 7"
                        when 'month'
                          "#{options[:ratings_table_name]}.days_taken > 7 AND #{options[:ratings_table_name]}.days_taken <= 30"
                        when 'season'
                          "#{options[:ratings_table_name]}.days_taken > 30 AND #{options[:ratings_table_name]}.days_taken <= 90"
                        when 'half_year'
                          "#{options[:ratings_table_name]}.days_taken > 90 AND #{options[:ratings_table_name]}.days_taken <= 180"
                        when 'year'
                          "#{options[:ratings_table_name]}.days_taken > 180 AND #{options[:ratings_table_name]}.days_taken <= 365"
                        when 'inf'
                          "#{options[:ratings_table_name]}.days_taken > 365"
                        when 'U'
                          "#{options[:ratings_table_name]}.days_taken IS NULL"
                        else
                          '1'
                        end
    "#{sex_filter} AND #{age_filter} AND #{time_taken_filter}"
  end
end